Skip to content

Add MongoDB persistence and native transaction enlistment - #242

Draft
thomhurst wants to merge 1 commit into
mainfrom
issue-233-mongodb-persistence
Draft

thomhurst wants to merge 1 commit into
mainfrom
issue-233-mongodb-persistence

Conversation

@thomhurst

@thomhurst thomhurst commented Nov 2, 2026 •

Copy link
Copy Markdown
Owner

Adds the MongoDB persistence foundation for #42: native transaction enlistment, explicit schema deployment, named durable storage, bounded reads and fenced claims. Application writes and outgoing rows share the caller's native transaction. Original UUIDv7 identity, binary payloads, duplicate/binary headers, ordering keys and exact UTC instants survive storage.

Release blocker: Strict trimming and Native AOT publication failed with MongoDB.Driver 3.13.0. The current release, 3.14.1, retains the dynamic serializer construction behind the recorded diagnostics. Strict publication with 3.14.1 remains unverified. Keep this draft and #233 on hold until a supported driver path passes strict publication and runtime smoke testing with diagnostics enabled. See #233 for the latest source check and release gate. Upstream AOT tracking

This implements the storage/enlistment child. MongoDB inbox handling remains #234; commit-triggered dispatch, lane ownership, poison rows, recovery and retention remain #235. Parent #42 stays open. Registration alone does not deliver stored messages or advertise scheduling support.

Closes #233

Native and existing features reused:

  • Native IClientSessionHandle, StartTransaction, commit/abort and WithTransactionAsync retry. Relayer associates one native transaction and writes immediately, without a commit wrapper or replacement retry protocol.
  • Native collection creation, indexes, atomic conditional updates/deletes, UUID binary representation, RawBsonDocument and ByteArrayBuffer. D40 explains why the fixed-schema encoder uses reusable capacity instead of the whole-array BsonBinaryWriter.WriteBytes(byte[]) API for arbitrary borrowed memory slices.
  • Existing IOutboxStore, IOutboxEnlistment, keyed DI and Options contracts. New provider-independent store tests run against both PostgreSQL and a MongoDB replica-set Testcontainers deployment.

Validation:

  • Final rebased Release solution build: zero warnings/errors. MongoDB suite: 13 passed; full PostgreSQL suite: 198 passed. Tests cover atomic commit/abort, borrowed memory, native retries, transaction replacement, indexed deployment, standalone rejection, eligibility, competing claims, stale fencing, expiry recovery and corrupt-header bounds.
  • npm ci and production documentation builds pass, including after rebase. The unchanged 19 moderate/3 low audit findings already have dispositions in website/README.md and Address documentation dependency audit vulnerabilities #101/fix: patch documentation tooling dependencies #200.
  • Strict dotnet publish tests/Relayer.Outbox.MongoDB.AotSmoke -c Release -r win-x64 fails in driver/BSON analysis (IL3050, IL2070 and related diagnostics). No repository warning guard is disabled.
  • Diagnostic publication explicitly sets IlcTreatWarningsAsErrors=false and ILLinkTreatWarningsAsErrors=false on the command line only. Its final-head native executable passes real schema, native transaction, read, count, claim, renewal, failure and completion operations against MongoDB 8.0.16. Constructor roots preserve native built-ins without changing global serializer configuration. This narrow runtime result does not establish general driver AOT safety.
  • BenchmarkDotNet Dry validates four payload/ordering cases. A representative default job reports 0 B for reusable encoding. These local codec measurements exclude native driver I/O/wrappers and do not establish an end-to-end throughput budget. Per outgoing row: one reusable BSON encoding/copy pass and one native transactional insert; no change to existing direct send/receive paths.
  • Full diff/code-simplifier review and Test-AssertPrGreenChecks.ps1 pass. Full solution tests and Linux hosted execution were not run locally.

Rebased onto b955339, preserving Protobuf changes at shared insertion points. The provider, shared tests and codec benchmark sources are unchanged by rebase. Earlier test/benchmark results precede the rebase; final solution build, documentation build and diagnostic native smoke use b8482f9.

Evidence: C:/git/Relayer-evidence/pr-242/b8482f94a63b00f76bfc5256974bd766abff28d1/. All 438 copied files were verified against originals by SHA-256. The archive includes raw logs/reports, benchmark harness and loaded binaries, final source and diagnostic AOT executable. provenance.txt distinguishes earlier measurements from final rebuilt test binaries. Local retention lasts while this PR remains open; closed-item cleanup may remove it. No generated evidence is committed.

Shared test extraction shipped in #245 (2475655), closing #244. On resumption, rebase onto current main and reuse tests/Shared/OutboxStoreContractTests.cs, including its UTC eligibility cases; retain only MongoDB-specific adaptation here. The strict native-driver AOT hold remains unchanged.

Latest release check (2026-11-23): MongoDB.Driver 3.14.1 remains the latest stable release. CSHARP-4840 remains unresolved with no fix version. See #233 for the released serializer source check.

Before resuming review, address the keyed enlistment finding and add its registration test. PR #1196 fixed the same guard in the shipped providers. The draft still owns the MongoDB registration change.

@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@thomhurst thomhurst added performance Run the advisory benchmark regression gate on this PR on-hold Waiting for an external dependency or gate labels Nov 2, 2026
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #242: MongoDB persistence and native transaction enlistment

I read the store, enlistment, BSON buffer, registration and schema code against AGENTS.md. I did not build or run the tests.

What looks sound

  • It wraps the native driver. It uses the caller's IMongoDatabase and session, and Relayer never commits or aborts the transaction (D1, D6).
  • The per-message write path encodes BSON into one reusable buffer. I checked the size patching, the binary header list and the ordering_key subtype-0 layout, and they are consistent.
  • The lane hash is the same FNV-1a over the key bytes that the PostgreSQL store uses, so lane assignment matches across stores.
  • Claim fencing is correct: claims are filtered on claim_token and an unexpired claim_expires_at_utc_ticks, and renewal uses $max. The partial index on status: pending matches the query shape.
  • Schema deployment is explicit and idempotent. It rejects standalone servers up front.

Non-blocking notes

  1. Binding.Dispose in MongoDBOutbox.cs throws InvalidOperationException if a send is still in flight. A throwing Dispose inside a using or finally can hide the original exception. It is only reachable through concurrent misuse, which the sequential-send guard already rejects. Consider making it non-throwing, for example by marking the binding inactive and letting the in-flight write fail.
  2. ReadPendingAsync follows the collection's read preference. If an app configures secondary reads, the pending list can be stale. Claims still fence on the primary, so correctness holds. A note in the docs would help.
  3. As the PR description says, this draft is blocked by the MongoDB.Driver AOT diagnostics (CSHARP-4840), and the strict AOT CI step stays enabled. It must stay a draft until that is resolved. I did not review the AOT setup further.

Per-message cost: one reusable buffer, with no per-message allocation in the encoder. The rest of the allocation story is unchanged from what the PR describes.

No actionable defects found.

@thomhurst

Copy link
Copy Markdown
Owner Author

Disposition of the Claude review on b8482f9:

  1. Non-blocking concurrent-misuse suggestion declined. The native session requires sequential operations, and the documented association lifetime requires awaiting sends before disposal. Making disposal clear an active binding could permit reuse of the scope while its native write still borrows the buffer. Keep the explicit failure rather than change that boundary in a disposition-only push.
  2. Non-blocking documentation suggestion declined for this cycle. Native read preference remains caller-owned, as the reference already states for native configuration. Stale secondary reads cannot bypass the primary conditional claim/fencing mutation. No behavioral defect or unsupported freshness guarantee was identified.
  3. Confirmed: the issue and draft stay on hold for the native driver's strict AOT diagnostics. No promotion or auto-merge is armed.

No unresolved review threads were present. The CLEAR verdict does not remove the upstream release blocker.

@thomhurst

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-02T14:36:12.696399Z b8482f9 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: b8482f94a6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

Review of #242 (MongoDB outbox storage foundation)

I read the store, its fenced-claim filters and the header codec against AGENTS.md and found no actionable defects. I did not run the build or tests.

  • Native features: the store uses the native session and transaction, conditional UpdateOne/DeleteOne, the Standard UUID representation and FindOptions limit and batch size. It adds no parallel retry or transaction protocol.
  • Claims and fencing: TryClaimAsync matches only rows that are pending, due and have no live claim. RenewClaimAsync, CompleteAsync and RecordFailureAsync match on the message ID, the claim token and an unexpired claim_expires_at_utc_ticks. MatchedCount and DeletedCount are checked. RenewClaimAsync uses $max, so an expiry can never move backwards.
  • Bounded reads: ReadPendingAsync limits the query to destination.Length and sorts by _id. Header slots are reused per scoped store, and the header decoder validates the count and every length, so malformed bytes raise FormatException instead of reading past the buffer.
  • Per-message path: the read path allocates only for the document itself, and the header slot cache is reused for stable header sets. Neither ReadPendingAsync nor the claim methods use reflection, LINQ or capturing lambdas.
  • Tests and docs: the shared store contract runs against both PostgreSQL and a MongoDB replica set. Enlistment and schema tests, the decision record and the site pages are included.
  • Earlier feedback: the non-blocking items from the previous review cycle were dispositioned with reasons. No unresolved threads remain.

Release blocker, unchanged: MongoDB.Driver 3.13.0 still fails strict trimming and Native AOT publication (CSHARP-4840). The PR description says to keep this draft on hold, so it must not be promoted or auto-merged until a driver version passes the strict publish smoke step. This is an existing, documented hold, not a new code finding.

@thomhurst

thomhurst commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner Author

Corrected the stale #245 draft reference: its shared suite is on main (2475655). MongoDB.Driver 3.13.0 is still the latest release, so the strict publication hold remains; this draft stays unarmed.

2026-11-13 triage: Latest release check (2026-11-13): MongoDB.Driver 3.14.0 shipped on November 12. It contains discriminator security fixes and breaking changes, so adopt that release or newer when resuming. The previously reproduced strict publish failure is for 3.13.0; no new 3.14.0 publish result is claimed. CSHARP-4840 remains unresolved with no fix version, and the released BsonClassMapSerializationProvider and BsonSerializationProviderBase retain the unannotated MakeGenericType/Activator serializer construction behind the recorded diagnostics. Keep on-hold until a supported native path passes strict publication and runtime smoke; a newer version number alone does not meet the gate. Current draft head is 80edb53. No unresolved threads or new code findings; historical validation remains attached to its named heads. Shared store tests are already on main through #245.

@thomhurst
thomhurst force-pushed the issue-233-mongodb-persistence branch from bd134bf to 80edb53 Compare November 10, 2026 12:16
@github-actions

Copy link
Copy Markdown

Review of #242 (MongoDB outbox storage foundation), head 80edb53

I re-read the store and header codec on this rebased head and compared them with the previous CLEAR review. I found no new actionable defects. I did not run the build or tests.

  • Native features: the store uses the native session and transaction, conditional UpdateOne/DeleteOne, Standard UUID representation and FindOptions limit and batch size. There is no parallel retry or transaction protocol (D1, D42).
  • Fencing: claims match on the message ID, the token and an unexpired claim. Renewal uses $max, so expiry never moves backwards. Mutations check MatchedCount and DeletedCount.
  • Bounded reads: the query limit equals destination.Length. The header decoder validates the count, every length and trailing bytes, so corrupt rows throw FormatException.
  • Per-message cost: header slots are reused per scoped store, there is no reflection or LINQ, and the codec benchmark covers the encoding path.
  • Tests and docs: the shared store contract, enlistment and schema tests, the decision record and the site pages are in place.

Release blocker, unchanged: MongoDB.Driver 3.13.0 still fails strict trimming and Native AOT publication (CSHARP-4840). The PR description and the maintainer's latest comment keep this draft on hold. It must not be marked ready or auto-merged until the strict publish smoke step passes without suppressing diagnostics. This is a documented hold, not a new code finding.

@thomhurst

Copy link
Copy Markdown
Owner Author

The enlistment guard in MongoDBOutboxRegistration.cs counts keyed IOutboxEnlistment descriptors. A consumer that registers an independent keyed enlistment before enabling MongoDB enlistment hits the duplicate-service exception. The sender resolves the unkeyed service, so the guard should check !descriptor.IsKeyedService. A registration-only test can add a keyed enlistment first, then verify both services resolve independently. This is the same DI behavior tracked for the SQL integrations in #1084.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

on-hold Waiting for an external dependency or gate performance Run the advisory benchmark regression gate on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MongoDB persistence and native transaction enlistment

1 participant